package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.model.VipOrder;
import com.example.demo.model.Product;
import com.example.demo.service.StoreService;
import com.example.demo.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/store")
public class StoreController {
    private final StoreService storeService;

    @Autowired
    public StoreController(StoreService storeService) {
        this.storeService = storeService;
    }

    @GetMapping("/products")
    public Response<List<Product>> getAvailableProducts() {
        return Response.success(storeService.getAvailableProducts());
    }

    @PostMapping("/purchase")
    public Response<Map<String, Object>> purchaseProduct(@RequestParam Long productId) {
        Long userId = getCurrentUserId();
        return Response.success(storeService.purchaseProduct(userId, productId));
    }

    @GetMapping("/orders")
    public Response<List<VipOrder>> getUserOrders() {
        Long userId = getCurrentUserId();
        return Response.success(storeService.getUserOrders(userId));
    }

    private Long getCurrentUserId() {
        return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
    }
}